package qlsl.androiddesign.api.util.commonutil;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Point;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

import qlsl.androiddesign.api.application.SoftwareApplication;


@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class TDevice
{
    // 手机网络类型
    public static final int NETTYPE_WIFI = 0x01;
    public static final int NETTYPE_CMWAP = 0x02;
    public static final int NETTYPE_CMNET = 0x03;

    public static boolean GTE_HC;
    public static boolean GTE_ICS;
    public static boolean PRE_HC;
    public static boolean CURRENT_SYSTEM_VERSION;
    private static Boolean _hasBigScreen = null;
    private static Boolean _hasCamera = null;
    private static Boolean _isTablet = null;
    private static Integer _loadFactor = null;

    private static int _pageSize = -1;
    public static float displayDensity = 0.0F;

    static
    {
        GTE_ICS = Build.VERSION.SDK_INT >= 14;
        GTE_HC = Build.VERSION.SDK_INT >= 11;
        PRE_HC = Build.VERSION.SDK_INT >= 11 ? false : true;
        CURRENT_SYSTEM_VERSION = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

    public TDevice()
    {
    }

    public static float dpToPixel(float dp)
    {
        return dp * (getDisplayMetrics().densityDpi / 160F);
    }

    public static int getDefaultLoadFactor()
    {
        if (_loadFactor == null)
        {
            Integer integer = Integer.valueOf(0xf & SoftwareApplication.getInstance()
                    .getResources().getConfiguration().screenLayout);
            _loadFactor = integer;
            _loadFactor = Integer.valueOf(Math.max(integer.intValue(), 1));
        }
        return _loadFactor.intValue();
    }

    public static float getDensity()
    {
        if (displayDensity == 0.0)
            displayDensity = getDisplayMetrics().density;
        return displayDensity;
    }

    public static DisplayMetrics getDisplayMetrics()
    {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        ((WindowManager) SoftwareApplication.getInstance().getSystemService(
                Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(
                displaymetrics);
        return displaymetrics;
    }

    public static float getScreenHeight()
    {
        return getDisplayMetrics().heightPixels;
    }

    public static float getScreenWidth()
    {
        return getDisplayMetrics().widthPixels;
    }

    /***
     * 获取设备的正真的大小
     */
    public static int[] getRealScreenSize(Activity activity)
    {
        int[] size = new int[2];
        int screenWidth = 0, screenHeight = 0;
        WindowManager w = activity.getWindowManager();
        Display d = w.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        d.getMetrics(metrics);
        // since SDK_INT = 1;
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
        // includes window decorations (statusbar bar/menu bar)
        if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
            try
            {
                screenWidth = (Integer) Display.class.getMethod("getRawWidth")
                        .invoke(d);
                screenHeight = (Integer) Display.class
                        .getMethod("getRawHeight").invoke(d);
            }
            catch (Exception ignored)
            {
            }
        // includes window decorations (statusbar bar/menu bar)
        if (Build.VERSION.SDK_INT >= 17)
            try
            {
                Point realSize = new Point();
                Display.class.getMethod("getRealSize", Point.class).invoke(d,
                        realSize);
                screenWidth = realSize.x;
                screenHeight = realSize.y;
            }
            catch (Exception ignored)
            {
            }
        size[0] = screenWidth;
        size[1] = screenHeight;
        return size;
    }

    /****
     * 获取状态栏的高度
     */
    public static int getStatusBarHeight()
    {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0;
        try
        {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            return SoftwareApplication.getInstance().getResources()
                    .getDimensionPixelSize(x);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getUdid()
    {
        String udid = String.format("%s", UUID.randomUUID());
        return udid;
    }

    /**
     * 判断是否是大屏幕
     **/
    public static boolean hasBigScreen()
    {
        boolean flag = true;

        if (_hasBigScreen == null)
        {
            boolean flag1;
            if ((0xf & SoftwareApplication.getInstance().getResources()
                    .getConfiguration().screenLayout) >= 3)
                flag1 = flag;
            else
                flag1 = false;
            Boolean boolean1 = Boolean.valueOf(flag1);
            _hasBigScreen = boolean1;
            if (!boolean1.booleanValue())
            {
                if (getDensity() <= 1.5F)
                    flag = false;
                _hasBigScreen = Boolean.valueOf(flag);
            }
        }
        return _hasBigScreen.booleanValue();
    }

    /***
     * 判断是否有相机
     */
    public static final boolean hasCamera()
    {
        if (_hasCamera == null)
        {
            PackageManager pckMgr = SoftwareApplication.getInstance()
                    .getPackageManager();
            boolean flag = pckMgr
                    .hasSystemFeature("android.hardware.camera.front");
            boolean flag1 = pckMgr.hasSystemFeature("android.hardware.camera");
            boolean flag2;
            if (flag || flag1)
                flag2 = true;
            else
                flag2 = false;
            _hasCamera = Boolean.valueOf(flag2);
        }
        return _hasCamera.booleanValue();
    }

    public static boolean hasHardwareMenuKey(Context context)
    {
        boolean flag = false;
        if (PRE_HC)
            flag = true;
        else if (GTE_ICS)
        {
            flag = ViewConfiguration.get(context).hasPermanentMenuKey();
        }
        else
            flag = false;
        return flag;
    }


    /****
     * 判断是否有谷歌应用市场
     */
    public static boolean gotoGoogleMarket(Activity activity, String pck)
    {
        try
        {
            Intent intent = new Intent();
            intent.setPackage("com.android.vending");
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=" + pck));
            activity.startActivity(intent);
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断包是否存在
     **/
    public static boolean isPackageExist(String pckName)
    {
        try
        {
            PackageInfo pckInfo = SoftwareApplication.getInstance().getPackageManager()
                    .getPackageInfo(pckName, 0);
            if (pckInfo != null)
                return true;
        }
        catch (NameNotFoundException e)
        {
        }
        return false;
    }

    /***
     * 隐藏动画视图
     */
    public static void hideAnimatedView(View view)
    {
        if (PRE_HC && view != null)
            view.setPadding(view.getWidth(), 0, 0, 0);
    }

    /***
     * 隐藏输入文字
     */
    public static void hideSoftKeyboard(View view)
    {
        if (view == null)
            return;
        ((InputMethodManager) SoftwareApplication.getInstance().getSystemService(
                Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                view.getWindowToken(), 0);
    }

    /***
     * 判断横竖屏，竖为真
     **/
    public static boolean isLandscape()
    {
        boolean flag;
        if (SoftwareApplication.getInstance().getResources().getConfiguration().orientation == 2)
            flag = true;
        else
            flag = false;
        return flag;
    }

    public static boolean isPortrait()
    {
        boolean flag = true;
        if (SoftwareApplication.getInstance().getResources().getConfiguration().orientation != 1)
            flag = false;
        return flag;
    }

    public static boolean isTablet()
    {
        if (_isTablet == null)
        {
            boolean flag;
            if ((0xf & SoftwareApplication.getInstance().getResources()
                    .getConfiguration().screenLayout) >= 3)
                flag = true;
            else
                flag = false;
            _isTablet = Boolean.valueOf(flag);
        }
        return _isTablet.booleanValue();
    }

    public static float pixelsToDp(float f)
    {
        return f / (getDisplayMetrics().densityDpi / 160F);
    }

    public static void showAnimatedView(View view)
    {
        if (PRE_HC && view != null)
            view.setPadding(0, 0, 0, 0);
    }


    public static boolean isSdcardReady()
    {
        return Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState());
    }

    public static String getCurCountryLan()
    {
        return SoftwareApplication.getInstance().getResources().getConfiguration().locale
                .getLanguage()
                + "-"
                + SoftwareApplication.getInstance().getResources().getConfiguration().locale
                .getCountry();
    }


    public static boolean isZhCN()
    {
        String lang = SoftwareApplication.getInstance().getResources()
                .getConfiguration().locale.getCountry();
        if (lang.equalsIgnoreCase("CN"))
        {
            return true;
        }
        return false;
    }

    public static String percent(double p1, double p2)
    {
        String str;
        double p3 = p1 / p2;
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);
        str = nf.format(p3);
        return str;
    }

    public static String percent2(double p1, double p2)
    {
        String str;
        double p3 = p1 / p2;
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(0);
        str = nf.format(p3);
        return str;
    }

    public static void gotoMarket(Context context, String pck)
    {
        if (!isHaveMarket(context))
        {
            return;
        }
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("market://details?id=" + pck));
        if (intent.resolveActivity(context.getPackageManager()) != null)
        {
            context.startActivity(intent);
        }
    }

    public static boolean isHaveMarket(Context context)
    {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.SoftwareApplication_MARKET");
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);
        return infos.size() > 0;
    }

    public static void openSoftwareApplicationInMarket(Context context)
    {
        if (context != null)
        {
            String pckName = context.getPackageName();
            try
            {
                gotoMarket(context, pckName);
            }
            catch (Exception ex)
            {
                try
                {
                    String otherMarketUri = "http://market.android.com/details?id="
                            + pckName;
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(otherMarketUri));
                    context.startActivity(intent);
                }
                catch (Exception e)
                {

                }
            }
        }
    }

    /**
     * 是否全屏
     **/
    public static void setFullScreen(Activity activity)
    {
        WindowManager.LayoutParams params = activity.getWindow()
                .getAttributes();
        params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        activity.getWindow().setAttributes(params);
        activity.getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }

    /***
     * 关闭全屏
     */
    public static void cancelFullScreen(Activity activity)
    {
        WindowManager.LayoutParams params = activity.getWindow()
                .getAttributes();
        params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        activity.getWindow().setAttributes(params);
        activity.getWindow().clearFlags(
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }

    public static PackageInfo getPackageInfo(String pckName)
    {
        try
        {
            return SoftwareApplication.getInstance().getPackageManager()
                    .getPackageInfo(pckName, 0);
        }
        catch (NameNotFoundException e)
        {
        }
        return null;
    }

    /***
     * 获取版本号
     **/
    public static int getVersionCode()
    {
        int versionCode = 0;
        try
        {
            versionCode = SoftwareApplication
                    .getInstance()
                    .getPackageManager()
                    .getPackageInfo(SoftwareApplication.getInstance().getPackageName(),
                            0).versionCode;
        }
        catch (NameNotFoundException ex)
        {
            versionCode = 0;
        }
        return versionCode;
    }

    public static int getVersionCode(String packageName)
    {
        int versionCode = 0;
        try
        {
            versionCode = SoftwareApplication.getInstance().getPackageManager()
                    .getPackageInfo(packageName, 0).versionCode;
        }
        catch (NameNotFoundException ex)
        {
            versionCode = 0;
        }
        return versionCode;
    }

    /**
     * 获取appName
     */
    public static String getAppName(Context context)
    {
        try
        {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        }
        catch (NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public static String getVersionName()
    {
        String name = "";
        try
        {
            name = SoftwareApplication.getInstance()
                    .getPackageManager()
                    .getPackageInfo(SoftwareApplication.getInstance().getPackageName(),
                            0).versionName;
        }
        catch (NameNotFoundException ex)
        {
            name = "";
        }
        return name;
    }

    public static boolean isScreenOn()
    {
        PowerManager pm = (PowerManager) SoftwareApplication.getInstance()
                .getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }

    /***
     * 安装apk文件
     **/
    public static void installAPK(Context context, File file)
    {
        if (file == null || !file.exists())
            return;
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "SoftwareApplicationlication/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static Intent getInstallApkIntent(File file)
    {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "SoftwareApplicationlication/vnd.android.package-archive");
        return intent;
    }

    public static void openDial(Context context, String number)
    {
        Uri uri = Uri.parse("tel:" + number);
        Intent it = new Intent(Intent.ACTION_DIAL, uri);
        context.startActivity(it);
    }

    public static void openSMS(Context context, String smsBody, String tel)
    {
        Uri uri = Uri.parse("smsto:" + tel);
        Intent it = new Intent(Intent.ACTION_SENDTO, uri);
        it.putExtra("sms_body", smsBody);
        context.startActivity(it);
    }

    public static void openDail(Context context)
    {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void openSendMsg(Context context)
    {
        Uri uri = Uri.parse("smsto:");
        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 启动当前应用设置页面
     */
    public static void openAppSettings(Context context)
    {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }

    public static String getIMEI()
    {
        TelephonyManager tel = (TelephonyManager) SoftwareApplication.getInstance()
                .getSystemService(Context.TELEPHONY_SERVICE);
        return tel.getDeviceId();
    }

    public static String getPhoneType()
    {
        return Build.MODEL;
    }

    /***
     * 打开某个SoftwareApplication
     **/
    public static void openSoftwareApplication(Context context, String packageName)
    {
        Intent mainIntent = SoftwareApplication.getInstance().getPackageManager()
                .getLaunchIntentForPackage(packageName);
        if (mainIntent == null)
        {
            mainIntent = new Intent(packageName);
        }
        else
        {
        }
        context.startActivity(mainIntent);
    }

    public static boolean openSoftwareApplicationActivity(Context context, String packageName,
                                                          String activityName)
    {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        ComponentName cn = new ComponentName(packageName, activityName);
        intent.setComponent(cn);
        try
        {
            context.startActivity(intent);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    /***
     * 判断wifi是否打开
     **/
    public static boolean isWifiOpen()
    {
        boolean isWifiConnect = false;
        ConnectivityManager cm = (ConnectivityManager) SoftwareApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        // check the networkInfos numbers
        NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
        for (int i = 0; i < networkInfos.length; i++)
        {
            if (networkInfos[i].getState() == NetworkInfo.State.CONNECTED)
            {
                if (networkInfos[i].getType() == ConnectivityManager.TYPE_MOBILE)
                {
                    isWifiConnect = false;
                }
                if (networkInfos[i].getType() == ConnectivityManager.TYPE_WIFI)
                {
                    isWifiConnect = true;
                }
            }
        }
        return isWifiConnect;
    }

    /**
     * 卸载安装包
     **/
    public static void uninstallApk(Context context, String packageName)
    {
        if (isPackageExist(packageName))
        {
            Uri packageURI = Uri.parse("package:" + packageName);
            Intent uninstallIntent = new Intent(Intent.ACTION_DELETE,
                    packageURI);
            context.startActivity(uninstallIntent);
        }
    }

    /***
     * 剪切版
     ***/
    @SuppressWarnings("deprecation")
    public static void copyTextToBoard(String string)
    {
        if (TextUtils.isEmpty(string))
            return;
        ClipboardManager clip = (ClipboardManager) SoftwareApplication.getInstance()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clip.setText(string);
    }

    /**
     * 发送邮件
     *
     * @param context
     * @param subject 主题
     * @param content 内容
     * @param emails  邮件地址
     */
    public static void sendEmail(Context context, String subject,
                                 String content, String... emails)
    {
        try
        {
            Intent intent = new Intent(Intent.ACTION_SEND);
            // 模拟器
            // intent.setType("text/plain");
            intent.setType("message/rfc822"); // 真机
            intent.putExtra(Intent.EXTRA_EMAIL, emails);
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
            intent.putExtra(Intent.EXTRA_TEXT, content);
            context.startActivity(intent);
        }
        catch (ActivityNotFoundException e)
        {
            e.printStackTrace();
        }
    }

    /***
     * 获取StatuBarHeight高度
     **/
    public static int getStatuBarHeight()
    {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, sbar = 38;// 默认为38，大部分是这样的
        try
        {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = SoftwareApplication.getInstance().getResources()
                    .getDimensionPixelSize(x);

        }
        catch (Exception e1)
        {
            e1.printStackTrace();
        }
        return sbar;
    }


    public static boolean hasStatusBar(Activity activity)
    {
        WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
        if ((attrs.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager
                .LayoutParams.FLAG_FULLSCREEN)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    /**
     * 调用系统安装了的应用分享
     *
     * @param context
     * @param title
     * @param url
     */
    public static void showSystemShareOption(Activity context,
                                             final String title, final String url)
    {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "分享：" + title);
        intent.putExtra(Intent.EXTRA_TEXT, title + " " + url);
        context.startActivity(Intent.createChooser(intent, "选择分享"));
    }

    /**
     * 获取当前网络类型
     *
     * @return 0：没有网络 1：WIFI网络 2：WAP网络 3：NET网络
     */
    public static int getNetworkType()
    {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) SoftwareApplication
                .getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null)
        {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE)
        {
            String extraInfo = networkInfo.getExtraInfo();
            if (!StringUtils.isEmpty(extraInfo))
            {
                if (extraInfo.toLowerCase().equals("cmnet"))
                {
                    netType = NETTYPE_CMNET;
                }
                else
                {
                    netType = NETTYPE_CMWAP;
                }
            }
        }
        else if (nType == ConnectivityManager.TYPE_WIFI)
        {
            netType = NETTYPE_WIFI;
        }
        return netType;
    }

    /**
     * 用来判断服务是否运行.
     *
     * @param context   the context
     * @param className 判断的服务名字 "com.xxx.xx..XXXService"
     * @return true 在运行 false 不在运行
     */
    public static boolean isServiceRunning(Context context, String className)
    {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context
                .ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> servicesList = activityManager
                .getRunningServices(Integer.MAX_VALUE);
        Iterator<ActivityManager.RunningServiceInfo> l = servicesList.iterator();
        while (l.hasNext())
        {
            ActivityManager.RunningServiceInfo si = (ActivityManager.RunningServiceInfo) l.next();
            if (className.equals(si.service.getClassName()))
            {
                isRunning = true;
            }
        }
        return isRunning;
    }

    /**
     * 停止服务.
     *
     * @param context   the context
     * @param className the class name
     * @return true, if successful
     */
    public static boolean stopRunningService(Context context, String className)
    {
        Intent intent_service = null;
        boolean ret = false;
        try
        {
            intent_service = new Intent(context, Class.forName(className));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        if (intent_service != null)
        {
            ret = context.stopService(intent_service);
        }
        return ret;
    }

    /**
     * 获取在该设备中可用的内核的数量，在所有处理器上。
     * Gets the number of cores available in this device, across all processors.
     * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
     *
     * @return The number of cores, or 1 if failed to get result
     */
    public static int getNumCores()
    {
        try
        {
            //Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            //Filter to only list the devices we care about
            File[] files = dir.listFiles(new FileFilter()
            {
                @Override
                public boolean accept(File pathname)
                {
                    //Check if filename is "cpu", followed by a single digit number
                    if (Pattern.matches("cpu[0-9]", pathname.getName()))
                    {
                        return true;
                    }
                    return false;
                }

            });
            //Return the number of cores (virtual CPU devices)
            return files.length;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return 1;
        }
    }

    /**
     * Gps是否打开
     * 需要<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />权限
     *
     * @param context the context
     * @return true, if is gps enabled
     */
    public static boolean isGpsEnabled(Context context)
    {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }


    /**
     * 描述：kill进程.
     *
     * @param context
     * @param pid
     */
    public static void killProcesses(Context context, int pid, String processName)
    {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context
                .ACTIVITY_SERVICE);
        String packageName = null;
        try
        {
            if (processName.indexOf(":") == -1)
            {
                packageName = processName;
            }
            else
            {
                packageName = processName.split(":")[0];
            }

            activityManager.killBackgroundProcesses(packageName);

            //
            Method forceStopPackage = activityManager.getClass().getDeclaredMethod
                    ("forceStopPackage", String.class);
            forceStopPackage.setAccessible(true);
            forceStopPackage.invoke(activityManager, packageName);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }


    /**
     * 描述：运行脚本.
     *
     * @param script
     * @return
     */
    public static String runScript(String script)
    {
        String sRet = "";
        try
        {
            final Process m_process = Runtime.getRuntime().exec(script);
            final StringBuilder sbread = new StringBuilder();
            Thread tout = new Thread(new Runnable()
            {
                public void run()
                {
                    BufferedReader bufferedReader = new BufferedReader(
                            new InputStreamReader(m_process.getInputStream()),
                            8192);
                    String ls_1 = null;
                    try
                    {
                        while ((ls_1 = bufferedReader.readLine()) != null)
                        {
                            sbread.append(ls_1).append("\n");
                        }
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    finally
                    {
                        try
                        {
                            bufferedReader.close();
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }
            });
            tout.start();

            final StringBuilder sberr = new StringBuilder();
            Thread terr = new Thread(new Runnable()
            {
                public void run()
                {
                    BufferedReader bufferedReader = new BufferedReader(
                            new InputStreamReader(m_process.getErrorStream()),
                            8192);
                    String ls_1 = null;
                    try
                    {
                        while ((ls_1 = bufferedReader.readLine()) != null)
                        {
                            sberr.append(ls_1).append("\n");
                        }
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    finally
                    {
                        try
                        {
                            bufferedReader.close();
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }
            });
            terr.start();

            int retvalue = m_process.waitFor();
            while (tout.isAlive())
            {
                Thread.sleep(50);
            }
            if (terr.isAlive())
                terr.interrupt();
            String stdout = sbread.toString();
            String stderr = sberr.toString();
            sRet = stdout + stderr;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
        return sRet;
    }

    /**
     * 应用程序运行命令获取 Root权限，设备必须已破解(获得ROOT权限)
     *
     * @return 应用程序是/否获取Root权限
     */
    public static boolean getRootPermission(Context context)
    {
        String packageCodePath = context.getPackageCodePath();
        Process process = null;
        DataOutputStream os = null;
        try
        {
            String cmd = "chmod 777 " + packageCodePath;
            //切换到root帐号
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        }
        catch (Exception e)
        {
            return false;
        }
        finally
        {
            try
            {
                if (os != null)
                {
                    os.close();
                }
                process.destroy();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 描述：获取可用内存.
     *
     * @param context
     * @return
     */
    public static long getAvailMemory(Context context)
    {
        //获取android当前可用内存大小
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context
                .ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo);
        //当前系统可用内存 ,将获得的内存大小规格化
        return memoryInfo.availMem;
    }

    /**
     * 描述：总内存.
     *
     * @param context
     * @return
     */
    public static long getTotalMemory(Context context)
    {
        //系统内存信息文件
        String file = "/proc/meminfo";
        String memInfo;
        String[] strs;
        long memory = 0;

        try
        {
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader, 8192);
            //读取meminfo第一行，系统内存大小
            memInfo = bufferedReader.readLine();
            strs = memInfo.split("\\s+");
            for (String str : strs)
            {
            }
            //获得系统总内存，单位KB
            memory = Integer.valueOf(strs[1]).intValue() * 1024;
            bufferedReader.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        //Byte转位KB或MB
        return memory;
    }
}
